package com.huixh.train.utils.random;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.huixh.train.utils.security.JwtUtil;
import jakarta.annotation.PostConstruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * 雪花算法随机生成
 *
 * @author huixh
 */
@Component
@ConfigurationProperties(prefix = "workspaces")
public class SnowUtil {
    private final Logger logger = LoggerFactory.getLogger(JwtUtil.class);
    private Long workerId;

    private Long datacenterId;

    @PostConstruct
    public void verifyConfig() {
        if (workerId == null || datacenterId == null) {
            logger.warn("workspaces.workerId 或 workspaces.datacenterId 未指定，后续操作可能出现生成冲突");
            workerId = RandomUtil.randomLong();
            datacenterId = RandomUtil.randomLong();
        }
    }

    public Long getWorkerId() {
        return workerId;
    }

    public void setWorkerId(Long workerId) {
        this.workerId = workerId;
    }

    public Long getDatacenterId() {
        return datacenterId;
    }

    public void setDatacenterId(Long datacenterId) {
        this.datacenterId = datacenterId;
    }

    public SnowUtil() {
    }

    public SnowUtil(Long workerId, Long datacenterId) {
        this.workerId = workerId;
        this.datacenterId = datacenterId;
    }

    /**
     * 雪花算法生成
     *
     * @return 唯一id
     */
    public Long getSnowflakeToLong() {
        return IdUtil.getSnowflake(workerId, datacenterId).nextId();
    }

    /**
     * 雪花算法生成
     *
     * @return 唯一id
     */
    public String getSnowflakeToString() {
        return Long.toString(IdUtil.getSnowflake(workerId, datacenterId).nextId());
    }
}
